package com.study.common.security;

import com.study.common.entity.User;
import com.study.common.enumerate.ExceptionInfo;
import com.study.login.entity.Identity;
import com.study.login.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

/**
 * @Create by ldr.
 * @create 2018-08-29 10:25
 * @Description：自定义验证
 */
public class MyPermission extends AuthorizingRealm {

    @Autowired
    @Qualifier(value = "loginService")
    private LoginService loginService;

    /**
     * description: 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // token中包含用户输入的用户名和密码
        //1. 从token中取出用户名
        String userName = (String) token.getPrincipal();

        //2.根据输入的userName从数据库中查询
        User user = loginService.getUserByUserName(userName);

        if (user == null) {
            return null;
        }

        //获取数据库中的密码
        String passWord = user.getPassWord();
        AuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(userName, passWord, this.getName());
        return authenticationInfo;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从principalCollection获取主身份信息
        // 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型）
        String userName = (String) principalCollection.getPrimaryPrincipal();
        User user = loginService.getUserByUserName(userName);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //查询出登陆用户的角色 添加该角色
        Identity identity = loginService.getIdentityByUser(userName);
        authorizationInfo.addRole(identity.getIdentityName());

        // 查询该用户的权限并 添加该权限
        List<String> stringList = loginService.getJurisdictionNameById(identity.getIdentityId());
        for (String s : stringList) {
            authorizationInfo.addStringPermission(s);
        }
        return authorizationInfo;
    }


}
